package controller

import (
	"gin-service/lib/GinSrv/GinResp"
	"gin-service/lib/GinSrv/GinRouter"
	"gin-service/lib/GormSrv"
	"gin-service/lib/GormSrv/model"
	"github.com/gin-gonic/gin"
)

func OrderController(router GinRouter.Router) {
	router.InitRouter()
	response := new(GinResp.RespImpl)

	router.Get("/query", func(ctx *gin.Context) {
		type OrderQuery struct {
			OrderId uint
			OrderCode string
			OrderNumber int
		}
		var orderList []OrderQuery

		orderId := ctx.Query("orderId")

		queryString := `select order_id, order_code, order_number from tbl_order where true`
		replacement := make([]interface{}, 0)

		if orderId != "" {
			queryString += ` and order_id = ?`
			replacement = append(replacement, 1)
		}

		GormSrv.GDB().Raw(queryString, replacement...).Scan(&orderList)

		response.DataResp(ctx, orderList)
	})

	router.Get("/select", func(ctx *gin.Context) {
		orderId := ctx.Query("orderId")

		if orderId != "" {
			var orderData model.Order
			GormSrv.GDB().First(&orderData, orderId)

			response.DataResp(ctx, orderData)
		} else {
			var orderList []model.Order
			GormSrv.GDB().Find(&orderList, orderId)

			response.DataResp(ctx, orderList)
		}
	})

	router.Get("/select/:orderId", func(ctx *gin.Context) {
		context := ctx.Copy()
		ch := make(chan interface{})

		go func() {
			orderId := context.Param("orderId")
			var order model.Order
			GormSrv.GDB().Find(&order, orderId)

			ch<- order
		}()

		result := <-ch
		close(ch)

		response.DataResp(ctx, result)
	})

	router.Post("/insert", func(ctx *gin.Context) {
		order := model.Order{}
		err := ctx.BindJSON(&order)
		if err != nil {
			panic(err.Error())
		}

		result := GormSrv.GDB().Create(&order)
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, order)
	})

	router.Put("/update", func(ctx *gin.Context) {
		orderId := ctx.Query("orderId")

		updateOrder := model.Order{}
		bindErr := ctx.BindJSON(&updateOrder)
		if bindErr != nil {
			panic(bindErr.Error())
		}

		findOrder := model.Order{}
		GormSrv.GDB().First(&findOrder, orderId)

		GormSrv.GDB().Save(&findOrder)

		response.DataResp(ctx, findOrder)
	})

	router.Put("/update/:orderId", func(ctx *gin.Context) {
		orderId := ctx.Param("orderId")

		updateOrder := model.Order{}
		bindErr := ctx.BindJSON(&updateOrder)
		if bindErr != nil {
			panic(bindErr.Error())
		}

		findOrder := model.Order{}
		GormSrv.GDB().First(&findOrder, orderId)
		GormSrv.GDB().Model(&findOrder).Updates(&updateOrder)

		response.DataResp(ctx, findOrder)
	})

	router.Delete("/delete", func(ctx *gin.Context) {
		orderId := ctx.Query("orderId")
		if orderId == "" {
			panic("orderId missing")
		}

		result := GormSrv.GDB().Unscoped().Delete(&model.Order{}, orderId)
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, result)
	})
}
